package com.imooc.router.gradle

import com.android.build.api.variant.AndroidComponentsExtension
import com.android.build.gradle.AppPlugin
import groovy.json.JsonSlurper
import org.gradle.api.Plugin
import org.gradle.api.Project

class RouterPlugin implements Plugin<Project> {

    @Override
    void apply(Project project) {
        if (!project.plugins.hasPlugin(AppPlugin)) {
            return
        }

        println("I am from RouterPlugin, apply from ${project.name}")
//        project.extensions.findByName("android").applicationVariants.all { variant ->
////            variant.javaCompileOptions.annotationProcessorOptions.arguments["root_project_dir"]= project.rootProject.projectDir.absolutePath
////            variant.javaCompileOptions.annotationProcessorOptions.arguments = ["root_project_dir": project.rootProject.projectDir.absolutePath]
//            println("RouterPlugin args >>>${variant.javaCompileOptions.annotationProcessorOptions.arguments}")
//        }
            println("RouterPlugin project.extensions >>>${project.extensions}")
//        if (project.extensions.findByName("kapt") != null) {
//            project.extensions.findByName("kapt").arguments {
//                arg("root_project_dir", project.rootProject.projectDir.absolutePath)
//                println("root_project_dir kapt >>>")
//            }
//            println("root_project_dir >>>")
//        }else{
//            println("kapt not root_project_dir >>>")
//        }
            project.getExtensions().create("router", RouterExtension)
            project.afterEvaluate {
                RouterExtension extension = project["router"]
                println("用户设置的wikiDir: ${extension.wikiDir}")
                //:app:compileDebugJavaWithJavac
                project.tasks.findAll { task ->
                    task.name.startsWith('compile') &&
                            task.name.endsWith('JavaWithJavac')
                }.each { task ->
                    task.doLast {
                        println(">>> markdown task start")
                        //根目录下的router_mapping目录
                        File routerMappingDir = new File(project.rootProject.projectDir, "router_mapping")
                        if (!routerMappingDir.exists()) {
                            return
                        }
                        File[] allChildFiles = routerMappingDir.listFiles()
                        if (allChildFiles.length < 1) {
                            return
                        }
                        StringBuilder markdownBuilder = new StringBuilder()
                        markdownBuilder.append("# 页面文档\n\n")

                        allChildFiles.each { child ->
                            if (child.name.endsWith(".json")) {
                                JsonSlurper jsonSlurper = new JsonSlurper()
                                def content = jsonSlurper.parse(child)
                                content.each { innerContent ->
                                    def url = innerContent['url']
                                    def description = innerContent['description']
                                    def realPath = innerContent['realPath']
                                    markdownBuilder.append("## $description\n")
                                    markdownBuilder.append("- url: $url\n")
                                    markdownBuilder.append("- realPath: $realPath\n\n")
                                }
                            }
                        }
                        File wikiFileDir = new File(extension.wikiDir)
                        if (!wikiFileDir.exists()) {
                            wikiFileDir.mkdir()
                        }

                        File wikiFile = new File(wikiFileDir, "页面文档.md")
                        if (wikiFile.exists()) {
                            wikiFile.delete()
                        }
                        wikiFile.write(markdownBuilder.toString())
                        println(">>> markdown task end")
                    }
                }
            }
            project.clean.doFirst {
                File routerMappingDir = new File(project.rootProject.projectDir, "router_mapping")
                if (routerMappingDir.exists()) {
                    routerMappingDir.deleteDir()
                }

            }
        }
    }